#Author: Tanyong
# *-* coding:utf8 *-*
# @time       : 2018/7/23 18:58
# @Author     : Tanyong
# @Site       : 
# @File       : views.py
# @Software   : PyCharm
from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for

from info import constants
from info import db
from info.models import User, Category, News
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import image_storage
from info.utils.response_code import RET


@profile_blu.route('/info')
@user_login_data
def user_info():
    """
    个人中心
    :return:
    """
    user = g.user
    if not user:
        # 如果未登录, 则重定向到首页中去
        return redirect(url_for("index.index"))

    data = {
        "user": user.to_dict()
    }
    return render_template('news/user.html', data=data)


@profile_blu.route("/base_info", methods=['GET', 'POST'])
@user_login_data
def base_info():
    """
    基本资料配置
    :return:
    """
    if request.method == 'GET':
        return render_template('news/user_base_info.html',data={'user': g.user.to_dict()})

    # 否则请求的是POST, 是对个人资料进行修改
    # 1, 取参数, 并判断参数的合法性
    params_dict = request.json
    nick_name = params_dict.get('nick_name')
    signature = params_dict.get("signature")
    gender = params_dict.get("gender")

    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if User.query.filter(User.nick_name==nick_name, User.nick_name != g.user.nick_name).first():
        return jsonify(errno=RET.PARAMERR, errmsg="用户名已注册, 请重新命名")

    # 2, 对用户的信息进行修改
    user = g.user
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    # 3, 将更改的信息提交到数据库中
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    # 4, 返回数据
    return jsonify(errno=RET.OK, errmsg="个人基本资料修改成功", data={'user': user.to_dict()})


@profile_blu.route('/pic_info', methods=['GET', "POST"])
@user_login_data
def pic_info():
    """
    头像上传
    :return:
    """
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={'user': g.user.to_dict()})

    # 否则请求的是POST, 是对进行头像上传
    # 1. 获取到上传的文件
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

    # 2. 再将文件上传到七牛云
    try:
        url = image_storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 将头像信息更新到当前用户的模型中
    user = g.user
    # 设置用户模型相关数据
    user.avatar_url = url
    # 将数据保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")

    # 4. 返回上传的结果<avatar_url>
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + url})


@profile_blu.route('/pass_info', methods=['GET', "POST"])
@user_login_data
def pass_info():
    """
    密码修改
    :return:
    """
    if request.method == "GET":
        return  render_template('news/user_pass_info.html')

    # 否则的话就是 进行密码修改
    # 1, 取参数, 并校验参数
    params_dict = request.json
    old_password = params_dict.get('old_password')
    new_password = params_dict.get('new_password')

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 2, 取出 源密码来进行密码校验
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    # 修改密码不能与原密码一致
    if old_password == new_password:
        return jsonify(errno=RET.PWDERR, errmsg="修改密码不能与原密码一致!")

    # 3, 进行密码修改
    user.password = new_password

    # 4, 将数据提交到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    # 5, 返回数据
    return jsonify(errno=RET.OK, errmsg="密码修改成功")


@profile_blu.route('/collection')
@user_login_data
def collection():
    """
    用户收藏
    :return:
    """
    user = g.user

    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.filter(user.id==user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_dict_li": news_dict_li
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    """
    新闻发布
    :return:
    """
    if request.method == 'GET':
        categories = []
        try:
            categories = Category.query.all()
            categories.remove(categories[0])
        except Exception as e:
            current_app.logger.error(e)

        return render_template('news/user_news_release.html', categories=categories)

    # 新闻发布
    # 1, 取参数,并校验
    params_dict = request.form
    title = params_dict.get('title')
    source = '个人发布'
    category_id = params_dict.get('category_id')
    digest = params_dict.get('digest')
    index_image = request.files.get('tindex_imageitle')
    content = params_dict.get('content')

    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2, 上传图片文件到 七牛云,并返回图片的路径
    # 2.1 尝试读取文件
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.IOERR, errmsg="文件读取错误")

    # 2.2 上传图片文件到 七牛云,并返回图片的路径
    try:
        key = image_storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛云出错")

    # 3, 创建news 模型,并赋值属性
    news = News()
    news.title = title
    news.source = source
    news.digest = digest
    news.content = content
    news.category_id = category_id
    news.user_id = g.user.id
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.status = 1

    # 4, 将对象存储到数据库中
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    # 5, 返回数据
    return jsonify(errno=RET.OK, errmsg="新闻发布成功, 等待审核中")


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    """
    新闻列表
    :return:
    """
    # 获取页数
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }

    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    """个人关注"""
    # 获取页数
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    """其他用户的信息"""
    other_id = request.args.get('user_id')
    user = g.user
    try:
        other_id = int(other_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    other = None
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    data = {
        "user": user.to_dict() if user else None,
        "other": other.to_dict() if other else None,
        "is_followed": is_followed
    }

    return render_template('news/other.html', data=data)


@profile_blu.route('/other_news_list')
def other_news_list():
    # 获取页数
    page = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([page, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)

